﻿using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Newtonsoft.Json;

namespace EnterpriseWebsiteUtil.Helper
{
    public class JWTHelper
    {
        public readonly IConfiguration config;

        public JWTHelper(IConfiguration config)
        {
            this.config = config;
        }


        public string GenerateJWT(object data,int expMinutes = 30)
        {
            var _jwtSecret = config["Jwt:Secret"];
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.UTF8.GetBytes(_jwtSecret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim("user",JsonConvert.SerializeObject(data)),
                }),
                Expires = DateTime.UtcNow.AddMinutes(expMinutes),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }
    }
}
